// pages/volunteer/index/index.js
const {
  citySubjectList,
  volunteerCity,
  volunteerCityType,
  addScore,
  getScore
} = require('../../../api/api')
const {
  voluntaryTemplateAdd,
  voluntaryTemplateGetuse
} = require('../../../api/ai')
const {
  decodeUserInfo
} = require('../../../api/login')
const {
  filterObj,
  throttle
} = require('../../../utils/util')
const {checkLogin} = require("../../../utils/util");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    scoreTypeList: [],
    bottomLift: getApp().globalData.bottomLift,
    subList: [],
    chooseList: [], //已选择列表
    mainSubject: null,
    checkedList: [],
    score: '',
    ranking: '',
    length: 3,
    cityList: [],
    cityIndex: 0,
    visible: false,
    toastVisible: false,
    config: {
      title: '请填写正确的信息',
      icon: "../images/warning_icon.png",
      duration: 3000
    },
    year: '2023',
    yearDisabled:false
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const subjectInfo = wx.getStorageSync('subjectInfo')
    this.setData({
      yearDisabled:wx.getStorageSync('yearDisabled')||false
    })
    if (!subjectInfo) {
      var userCitys = {
        code: 350000,
        name: "福建"
      }
      wx.setStorageSync('userCitys', userCitys)
      this.fetchCityList(userCitys.code)
      this.getCitySubject(userCitys.code)
      this.setData({
        disabled: subjectInfo ? false : true
      })
    } else {
      this.voluntaryTemplateGetuse()
    }

  },
  onShow() {
    const subjectInfo = wx.getStorageSync('subjectInfo')
    this.setData({
      disabled: subjectInfo ? true : false
    })
  },
  async voluntaryTemplateGetuse() {
    const {
      firstSelect,
      firstSelectSubjects,
      secondSelectSubjects,
      province,
      provinceId,
      score,
      ranking,
      year
    } = wx.getStorageSync('subjectInfo')
    this.setData({
      mainSubject: firstSelect || '',
      score: score,
      ranking: ranking,
      provinceId: provinceId,
      province: province,
      firstSelect: firstSelectSubjects,
      secondSelect: secondSelectSubjects,
      year
    })
    this.getVolunteerCityType(provinceId)
    this.getCitySubject(provinceId, firstSelectSubjects, secondSelectSubjects)
    return
    const {
      result
    } = await voluntaryTemplateGetuse()
    if (result) {
      const {
        provinceId,
        firstSelect,
        secondSelect
      } = result
      const {
        score,
        ranking,
      } = wx.getStorageSync('subjectInfo')
      //分数、位次使用最新数据
      this.setData({
        ...result,
        score,
        ranking,
        year: wx.getStorageSync('year') || '2023'
      })
      // this.fetchCityList(provinceId)
      this.getVolunteerCityType(provinceId)
      this.getCitySubject(provinceId, firstSelect, secondSelect)
    } else {
      const {
        firstSelect,
        firstSelectSubjects,
        secondSelectSubjects,
        province,
        provinceId,
        score,
        ranking,
        year
      } = wx.getStorageSync('subjectInfo')
      this.setData({
        mainSubject: firstSelect || '',
        score: score,
        ranking: ranking,
        provinceId: provinceId,
        province: province,
        firstSelect: firstSelectSubjects,
        secondSelect: secondSelectSubjects,
        year
      })
      // this.fetchCityList(provinceId)
      this.getVolunteerCityType(provinceId)
      this.getCitySubject(provinceId, firstSelectSubjects, secondSelectSubjects)
    }
  },
  async fetchCityList(provinceId) {
    const {
      result
    } = await volunteerCity()
    let cityList = []
    let cityIndex = 0
    result.map((item, index) => {
      if (item.provinceId == provinceId) {
        cityIndex = index
        this.setData({
          province: item.province,
          provinceId: item.provinceId
        })
      }
      cityList.push({
        province: item.province,
        provinceId: item.provinceId
      })

    })
    this.setData({
      cityList,
      cityIndex,
    })
  },
  //获取成绩类型
  async getVolunteerCityType(provinceId) {
    const {
      result
    } = await volunteerCityType(provinceId)
    var scoreTypeList = result.map((item, index) => {
      return {
        name: item.level1Name,
        level1Name: item.level1Name == '本科' ? '本科' : '专科（高职）',
        checked: false
      }
    })
    this.setData({
      scoreTypeList: scoreTypeList,
    })
  },
  async getCitySubject(provinceId, firstSelect, secondSelect) {
    const {
      result
    } = await citySubjectList(provinceId)
    //首选科目
    const mainList = result.filter(function (item, index, arr0) {
      return item.isPreferred > 0
    })
    const subjectList = result.filter(function (item, index, arr0) {
      return item.isPreferred == 0
    })
    var {
      mainSubject,
      checkedList,
      chooseList
    } = this.data
    if (firstSelect && firstSelect !== '') {
      const mainSubjectList = mainList.filter((item) => {
        return item.subjectsName == firstSelect
      })
      mainSubject = mainSubjectList[0].subjectsId
      checkedList.push(firstSelect)
      chooseList = chooseList.concat(mainSubjectList)
    }
    if (secondSelect && secondSelect !== '') {
      const secondSelectedArray = secondSelect.split(',')
      const hookSubjectList = subjectList.filter((item) => {
        return secondSelectedArray.indexOf(item.subjectsName) > -1
      })
      checkedList = checkedList.concat(secondSelectedArray)
      chooseList = chooseList.concat(hookSubjectList)
    }
    this.setData({
      list1: mainList,
    })
    if (checkedList.length > 0) {
      subjectList.map((item) => {
        item['choose'] = checkedList.indexOf(item.subjectsName) > -1 || checkedList.indexOf(item.subjectsId) > -1
      })
    } else {
      subjectList.map((item) => {
        item['choose'] = false
      })
    }
    this.setData({
      length: mainList.length > 0 ? 2 : 3,
      subList: subjectList,
      chooseList,
      checkedList,
      mainSubject,
      initCheckedList: checkedList
    })

  },
  bindPickerChange(e) {
    const {
      cityList
    } = this.data
    const index = parseInt(e.detail.value)
    const provinceId = cityList[index].provinceId
    const province = cityList[index].province
    this.setData({
      cityIndex: index,
      checkedList: [],
      chooseList: [],
      mainSubject: '',
      subList: [],
      list1: [],
      score: '',
      ranking: '',
      provinceId,
      province
    })
    this.getVolunteerCityType(provinceId)
    this.getCitySubject(provinceId)
  },
  checkItem(e) {
    const {
      index
    } = e.currentTarget.dataset
    const {
      scoreTypeList
    } = this.data
    scoreTypeList.map((item) => {
      item.checked = false
    })
    scoreTypeList[index].checked = true
    this.setData({
      scoreTypeList,
      visible: true
    })
  },
  chooseMain(e) {
    const {
      list1,
      chooseList,
      checkedList
    } = this.data
    const {
      id,
      name
    } = e.currentTarget.dataset
    const ids = checkedList
    if (ids.indexOf(id) > -1) return
    const deleteIds = list1.filter((item) => {
      return item.subjectsId !== id
    })
    const mainSubjectList = list1.filter((item) => {
      return item.subjectsId == id
    })
    const subjectsId = deleteIds[0].subjectsId
    chooseList.map((item, index) => {
      if (item.subjectsId == subjectsId) {
        chooseList.splice(index, 1)
      }
    })
    const newList = mainSubjectList.concat(chooseList)
    const newCheckedList = newList.map((item) => {
      return item.subjectsId
    })
    this.setData({
      mainSubject: id,
      firstSelect: name,
      chooseList: newList,
      checkedList: newCheckedList,
    })
    this.getRank()
  },
  chooseSubject(e) {
    const {
      id,
      choose,
      index,
      name
    } = e.currentTarget.dataset
    var {
      subList, //学科列表
      checkedList, //已选科目id
      chooseList, //已选科目
      length,
      mainSubject,
      list1
    } = this.data
    const hookSubjectList = chooseList.filter((item) => {
      return item.subjectsId !== mainSubject
    })
    const mainSubjectList = list1.filter((item) => {
      return item.subjectsId == mainSubject
    })
    const hookIds = hookSubjectList.map((item) => {
      return item.subjectsId
    })
    const mainIds = mainSubjectList.length > 0 ? mainSubjectList.map((item) => {
      return item.subjectsId
    }) : []
    subList[index].choose = !choose
    if (choose) {
      //删除
      const index = hookIds.indexOf(id)
      hookIds.splice(index, 1)
      hookSubjectList.splice(index, 1)
    } else {
      if (hookIds.length >= length) {
        subList.map((item) => {
          if (item.subjectsId == hookIds[0]) {
            item.choose = false
          }
        })
        hookIds.splice(0, 1, id)
        hookSubjectList.splice(0, 1, subList[index])
      } else {
        hookIds.push(id)
        hookSubjectList.push(subList[index])
      }
    }
    chooseList = mainSubjectList.concat(hookSubjectList.sort((a, b) => {
      return a.id - b.id
    }))
    const secondSelectArray = hookSubjectList.map((item) => {
      return item.subjectsName
    })
    checkedList = mainIds.concat(hookIds)
    this.setData({
      subList,
      checkedList,
      secondSelect: secondSelectArray.join(','),
      chooseList
    })
    this.getRank()

  },
  async getRank() {
    const {
      score,
      mainSubject,
      chooseList,
      provinceId,
    } = this.data
    if (!mainSubject && chooseList.length < 3) return
    const ranking = await getApp().getRank(score,
      provinceId,
      '2022',
      mainSubject,
      chooseList)
    this.setData({
      ranking
    })
  },
  inputChange(e) {
    const {
      type
    } = e.currentTarget.dataset
    this.setData({
      [type]: e.detail.value
    })
    if (type == 'score' && e.detail.value.length == 3) {
      if (e.detail.value < 100 || e.detail.value > 750) {
        wx.showToast({
          title: '请输入100-750区间的整数',
          icon: 'none'
        })
        this.setData({
          ranking: ''
        })
        return
      }
      this.getRank()
    }
  },
  goto(e) {
    checkLogin().then(res=>{
      const {
        url
      } = e.currentTarget.dataset
      wx.navigateTo({
        url,
      })
    }).catch(e=>{
      wx.navigateTo({
        url: '/pages/login/index',
      })
    })
   
  },
  //更新info  添加志愿模板
  confirm: throttle(function () {
    var that = this
    this.validateForm().then(async function (res) {
      // if (!wx.getStorageSync('subjectInfo')) {
      const {
        checkedList,
        initCheckedList,
        chooseList
      } = that.data
      const chooseListStorage = wx.getStorageSync('chooseList')
      var chooseListIds = chooseList.map((item) => {
        return item.subjectsId
      })
      var chooseListStorageIds = (chooseListStorage || []).map((item) => {
        return item.subjectsId
      })
      //判断是否修改 对比模板+本地
      var flag = checkedList.sort().toString() == initCheckedList.sort().toString()
      //判断是否修改 对比本地
      var flag1 = chooseListIds.sort().toString() == chooseListStorageIds.sort().toString()
      checkLogin().then(async res=>{
        if (!flag) {
          await that.updateScore()
        }
      })
   
      that.voluntaryAdd()
    })
  }),
  validateForm() {
    const {
      score,
      ranking,
      chooseList,
      scoreTypeList,
    } = this.data

    var checked = scoreTypeList.filter((item) => {
      return item.checked
    })
    var flag = scoreTypeList.length > 0 ? checked.length > 0 ? true : false : true
    var scoreFlag = score !== '' && score != 0 && score <= 750 && score >= 150
    return new Promise((resolve) => {
      if (scoreFlag && ranking !== '' && chooseList.length >= 3 && flag) {
        resolve()
      } else {
        this.setData({
          toastVisible: true
        })
      }
    })
  },

  async updateScore(e) {
    var _this = this
    const {
      mainSubject,
      chooseList,
      score,
      ranking,
      currentRegion,
    } = _this.data
    const secondSelectList = chooseList.filter((item) => {
      return item.subjectsId !== mainSubject
    })
    const secondSelectIds = secondSelectList.map((item) => {
      return item.subjectsId
    })
    const params = {
      score,
      ranking,
      firstSelect: mainSubject,
      secondSelect: secondSelectIds.toString(),
    }
    const {
      result
    } = await addScore(params)
    wx.setStorageSync('chooseList', chooseList)
    _this.getScore()
  },
  async getScore() {
    var {
      result
    } = await getScore()
    const subjectList = wx.getStorageSync('subjectList') || await getApp().getSubjectList()
    const cityList = wx.getStorageSync('cityList') || await getApp().getCityList()
    const currentCityList = cityList.filter((item) => {
      return item.id == result.provinceId
    })
    let newTime = Math.round(new Date())
    const userCitys = {
      code: currentCityList[0].id,
      name: currentCityList[0].title,
      time: newTime
    }
    let checkedIds = []
    const secondSelect = result.secondSelect == '' ? [] : result.secondSelect.split(',')
    var firstSelectSubjects = ''
    var secondSelectSubjects = []
    subjectList.map((item) => {
      if (result.firstSelect !== '' && item.id == result.firstSelect) {
        firstSelectSubjects = item.name
        checkedIds.push(parseInt(result.firstSelect))
      }
      if (secondSelect.indexOf(item.id) > -1 || secondSelect.indexOf(item.id.toString()) > -1) {
        secondSelectSubjects.push(item.name)
        checkedIds.push(parseInt(item.id))
      }
    })
    result.firstSelectSubjects = firstSelectSubjects
    result.secondSelectSubjects = secondSelectSubjects.join(',')
    if (checkedIds.length > 0) {
      wx.setStorageSync('ids', checkedIds)
    }
    wx.setStorageSync('mainSubject', result.firstSelect == '' ? '' : parseInt(result.firstSelect))
    wx.setStorageSync('score', result.score)
    wx.setStorageSync('ranking', result.ranking)
    wx.setStorageSync('year', result.year)
    wx.setStorageSync('userCitys', userCitys)
    wx.setStorageSync('subjectInfo', result)
    this.triggerEvent('confirm')
  },
  async voluntaryAdd() {

    const {
      chooseList,
      score,
      mainSubject,
      ranking,
      province,
      provinceId
    } = this.data
    var firstSelect = ''
    var secondSelectArray = []
    chooseList.map((item) => {
      if (item.subjectsId == mainSubject) {
        firstSelect = item.subjectsName
      } else {
        secondSelectArray.push(item.subjectsName)
      }
    })
    let params = {
      firstSelect,
      province,
      provinceId,
      score,
      secondSelect: secondSelectArray.join(','),
      ranking: ranking
    }
    params = filterObj(params)
    checkLogin().then(async login=>{
      const res = await decodeUserInfo()
      if (res.result.vips.length <= 0) {
        wx.navigateTo({
          url: '/pages/article/vip/index?params=' + encodeURIComponent(JSON.stringify(params)),
        })
        return
      }
      const {
        result
      } = await voluntaryTemplateAdd(params)
      this.navigate(result)
    }).catch(e=>{
      this.navigate(params)
    })
  
  },
  navigate(result) {
    const {
      scoreTypeList
    } = this.data
    const levels = scoreTypeList.filter((item) => {
      return item.checked
    })
    const params = result
    params.level1Name = result.useBatch == '本科批' ? '本科' : '专科（高职）'
    wx.navigateTo({
      url: '/pages/volunteer/select/index?params=' + encodeURIComponent(JSON.stringify(params))
    })

  },
  intelligence() {
    checkLogin().then(res=>{
      var that = this
      const {
        score,
        ranking,
        firstSelect,
        secondSelect,
        provinceId,
        province
      } = this.data
      this.validateForm().then(async function (res) {
        const {
          checkedList,
          initCheckedList,
        } = that.data
        //判断是否修改 对比模板+本地
        var flag = checkedList.sort().toString() == initCheckedList.sort().toString()
        //判断是否修改 对比本地
        if (!flag) {
          await that.updateScore()
        }
        const params = {
          firstSelect,
          secondSelect,
          score,
          ranking,
          provinceId,
          province,
        }
        wx.navigateTo({
          url: '/pages/volunteer/intelligence/index?params=' + encodeURIComponent(JSON.stringify(params))
        })
      })
    }).catch(e=>{
      wx.navigateTo({
        url: '/pages/article/vip/index'
      })
    })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '德道升学',
      path: '/pages/volunteer/index/index?scene=' + wx.getStorageSync('userInfo').id,
      imageUrl: 'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  },
})
